package com.hsh.maoduo.config.realm;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hsh.maoduo.mapper.UserMapper;
import com.hsh.maoduo.pojo.entity.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class UserRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    /**
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * @param authenticationToken 封装了前端的账号密码
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        String md5pwd = new String((char[])authenticationToken.getCredentials());
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user==null){
            return null;
        }

        if (md5pwd.equals(user.getMd5pwd())){
            return new SimpleAuthenticationInfo(username,md5pwd,"salt");
        }

        return null;
    }
}
